

package cuttings;


import java.util.* ;
import java.io.*;

public class SendSocketsList
{
    static LinkedList sendsocketsList = new LinkedList();

    static public void addSendSocket(SendSockets newSocket)
    {
         sendsocketsList.add(newSocket);
    }

    static public void removeSendSocket(String IP)
    {
        int size = sendsocketsList.size();
        int i = 0;
        while(i<size)
        {
            SendSockets temp = (SendSockets) sendsocketsList.get(i);
            if (temp.userIP.equals(IP))
            {
                sendsocketsList.remove(i);
                break;
            }
            i++;
        }

    }

    static public void sendToAll (String message) throws Exception
    {
        int size = sendsocketsList.size();
        DataOutputStream outToSocket;
        System.out.println("In sendtoall:"+size);
        int i = 0;
        while(i<size)
        {
            SendSockets temp = (SendSockets) sendsocketsList.get(i);
            outToSocket = temp.opStream;
            outToSocket.writeBytes(message + "\r\n");
            System.out.println("Entered sendtoall:"+message);
            i++;
        }
    }


    static public void sendToPeer (String peername,String message) throws Exception
    {
        int size = sendsocketsList.size();
        DataOutputStream outToSocket;
        System.out.println("In sendtopeer:"+size);
        int i = 0;
        while(i<size)
        {
            SendSockets temp = (SendSockets) sendsocketsList.get(i);
            if(temp.userName.equals(peername))
            {
                outToSocket = temp.opStream;
                outToSocket.writeBytes(message + "\r\n");

                System.out.println("SentToPeer:"+message);
                break;
            }
            i++;
        }
    }

    static public void sendFileToPeer(String peername,byte[] mybytearray,String filename) throws Exception
    {
        int size = sendsocketsList.size();
        DataOutputStream outToSocket;
        System.out.println("In sendtopeer:"+size);
        int i = 0;
        while(i<size)
        {
            SendSockets temp = (SendSockets) sendsocketsList.get(i);
            if(temp.userName.equals(peername))
            {
                outToSocket = temp.opStream;

                outToSocket.writeBytes("#:file:"+mybytearray.length+":"+filename+":\r\n");
                Thread.sleep(1);
                System.out.println("Sending File:" + mybytearray.length);

                outToSocket.write(mybytearray,0, mybytearray.length);
                outToSocket.flush();

                System.out.println("SentFileToPeer");
                break;
            }
            i++;
        }


    }
}
